package com.xb.system.config;

import com.xb.model.domain.entity.PaymentOrder;
import com.xb.model.domain.entity.Userinfo;
import com.xb.system.mapper.db1.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * PaymentOrder查询结果拦截器
 * 自动填充phone字段
 */
@Slf4j
@Component
@Intercepts({
    @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class})
})
public class PaymentOrderInterceptor implements Interceptor {

    @Autowired
    private UserMapper userMapper;

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        // 执行原始查询
        Object result = invocation.proceed();
        
        // 如果结果是PaymentOrder或PaymentOrder列表，填充phone字段
        if (result != null) {
            try {
                if (result instanceof PaymentOrder) {
                    fillPhone((PaymentOrder) result);
                } else if (result instanceof List) {
                    List<?> list = (List<?>) result;
                    if (!list.isEmpty() && list.get(0) instanceof PaymentOrder) {
                        fillPhoneList((List<PaymentOrder>) list);
                    }
                } else if (result instanceof com.baomidou.mybatisplus.core.metadata.IPage) {
                    // 处理MyBatis-Plus的分页结果
                    com.baomidou.mybatisplus.core.metadata.IPage<?> page = (com.baomidou.mybatisplus.core.metadata.IPage<?>) result;
                    if (page.getRecords() != null && !page.getRecords().isEmpty()) {
                        Object firstRecord = page.getRecords().get(0);
                        if (firstRecord instanceof PaymentOrder) {
                            fillPhoneList((List<PaymentOrder>) page.getRecords());
                        }
                    }
                }
            } catch (Exception e) {
                // 填充phone失败不应该影响主流程，只记录日志
                log.warn("填充PaymentOrder phone字段时发生异常", e);
            }
        }
        
        return result;
    }

    /**
     * 填充单个PaymentOrder的phone字段
     */
    private void fillPhone(PaymentOrder order) {
        if (order == null || order.getUserId() == null || order.getUserId() == 0) {
            return;
        }
        
        try {
            Userinfo user = userMapper.selectById(order.getUserId());
            if (user != null) {
                order.setPhone(user.getPhone());
            }
        } catch (Exception e) {
            log.warn("填充PaymentOrder phone字段失败，userId: {}", order.getUserId(), e);
        }
    }

    /**
     * 批量填充PaymentOrder列表的phone字段
     */
    private void fillPhoneList(List<PaymentOrder> orders) {
        if (orders == null || orders.isEmpty()) {
            return;
        }
        
        // 收集所有需要查询的userId
        Set<Long> userIds = new HashSet<>();
        for (PaymentOrder order : orders) {
            if (order != null && order.getUserId() != null && order.getUserId() != 0) {
                userIds.add(order.getUserId());
            }
        }
        
        if (userIds.isEmpty()) {
            return;
        }
        
        try {
            // 批量查询用户信息
            Map<Long, String> userPhoneMap = new HashMap<>();
            for (Long userId : userIds) {
                try {
                    Userinfo user = userMapper.selectById(userId);
                    if (user != null && user.getPhone() != null) {
                        userPhoneMap.put(userId, user.getPhone());
                    }
                } catch (Exception e) {
                    log.warn("查询用户信息失败，userId: {}", userId, e);
                }
            }
            
            // 填充phone字段
            for (PaymentOrder order : orders) {
                if (order != null && order.getUserId() != null) {
                    String phone = userPhoneMap.get(order.getUserId());
                    if (phone != null) {
                        order.setPhone(phone);
                    }
                }
            }
        } catch (Exception e) {
            log.error("批量填充PaymentOrder phone字段失败", e);
        }
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {
        // 不需要配置属性
    }
}

